package com.dabay.web.job;


import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.dabay.web.module.Drugs;
import com.dabay.web.service.Drug_service;
import com.dabay.web.util.JsonPluginsUtil;
import com.dabay.web.util.NbwxUtil;
import com.dabay.web.util.TimeUtil;


@Component
public class MQInitQuartz_Drugs {
	
	private static Logger logger = LoggerFactory.getLogger(MQInitQuartz_Drugs.class);
	
	@Autowired
	private Drug_service drug_service;


	@Scheduled(cron = "0 07 1 ? * *")
	public void runFunction() {
		// 医保药品目录
		logger.info(new Date() + " 开始执行推送任务 --> 医保药品目录数据");
		sendMQsms();
		logger.info(new Date() + " 结束执行推送任务 --> 医保药品目录数据");
	}
	
	private void sendMQsms() {
		int yesterDayInt = new TimeUtil().getYesterdayInt();
		logger.info("药品目录同步开始过滤的最小日期是：-->"+yesterDayInt);
		//  医保药品目录
		String methods = "getYLBXYPMLList";
		String key = "";
		String result = "";
		try {
			result = NbwxUtil.getModelResult_listService(key, methods);
			if (StringUtils.isNotEmpty(result)) {
				try {
					List<com.dabay.web.module.Drugs> drugs_list = JsonPluginsUtil
							.jsonToBeanList(result,com.dabay.web.module.Drugs.class);
					if(drugs_list.size()>0){
						int thisNewReocrdCount = 0;
						for (Drugs drugs : drugs_list) {
							try {
								//数据过滤
								int newsDate = new TimeUtil().getIntByDateStr(drugs.getCrtime());
								if(newsDate<yesterDayInt){
									continue;
								}
								String zwmc = drugs.getZwmc();
								int count = drug_service.selectDrugs(zwmc);
								if (count == 0) {
									thisNewReocrdCount++;//记录数加1
									String create_time = TimeUtil.transTime();
									drugs.setCreate_time(create_time);
									drugs.setType("2");//默认是西药
									if(zwmc.indexOf("免煎")!=-1){
										drugs.setType("1");//带免煎的都是中药
									}
									drug_service.insertDrugs(drugs);
								}								
							} catch (Exception e) {
								e.printStackTrace();
								logger.info("error!! the data insert shibai == the Metadataid is"+drugs.getMetadataid());
								logger.info(new Date() + " 插入数据库失败 --> 医保药品目录数据");
							}
						}
						logger.info(new Date() + " 数据库更新数 --> "+thisNewReocrdCount+"医保药品目录数据");
					}					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	
		
}
